<script lang="ts">
	import UploadFile from "$lib/shared/components/upload/upload-knowledge.svelte";
	import UploadImage from "$lib/shared/components/upload/uploadImage.svelte";
    import { Button, Drawer, CloseButton } from "flowbite-svelte";
    import { InfoCircleSolid } from "flowbite-svelte-icons";
    import { sineIn } from "svelte/easing";
    import { getNotificationsContext } from "svelte-notifications";
	import { fetchAllFile,fetchKnowledgeBaseId,fetchKnowledgeBaseIdByPaste } from "$lib/network/upload/Network";
	import { knowledge1, knowledgeName, storageFiles } from "$lib/shared/stores/common/Store";
    import DocCard from "$lib/shared/components/doc_management/docCard.svelte";
	import PasteURL from "$lib/shared/components/upload/PasteKnowledge.svelte";
	import { Tabs, TabItem } from "flowbite-svelte";
	import NoFile from "$lib/assets/upload/no-file.svelte";
	import LoadingButton from "$lib/assets/upload/loading-button.svelte";


    // 导入图片上传网络请求函数
    import { uploadImageToServer } from "$lib/network/upload/Network";

    const { addNotification } = getNotificationsContext();
    
	export let overrideClasses = "";
	const classes = overrideClasses ? overrideClasses : `w-5 h-5 text-gray-400`;
	let isOpen = false;
	let dropdownRef;
	let showUploadImage = false;

    //图片上传逻辑
    let hidden6 = true;
	let uploading = false;
	let selectedFile: File | null = null;
	let imageUploaded = false;
	let autoCloseTimer: number | null = null;

	let transitionParamsRight = {
		x: 320,
		duration: 200,
		easing: sineIn,
	};

	function handleFileSelect(event: Event) {
		const input = event.target as HTMLInputElement;
		if (input.files && input.files.length > 0) {
			selectedFile = input.files[0];
		} else {
			console.log("null");
			selectedFile = null; // 如果没有文件，设置为空
		}
	}

	async function handleImageUpload() {
		if (!selectedFile) {
			showNotification("请选择图片", "error");
			return;
		}

		uploading = true;
		const formData = new FormData();
		if (selectedFile instanceof File) {
			const newFileName = "test.png"; // 设定新文件名

			const renamedFile = new File([selectedFile], newFileName, {
				type: selectedFile.type,
			});

			formData.append("file", renamedFile, renamedFile.name);
		} else {
			showNotification("上传文件无效", "error");
			uploading = false;
			return;
		}
		formData.forEach((value, key) => {
			console.log(key, value);
		});
		try {
			const res = await uploadImageToServer(formData);
			console.log('完整响应:', res); // 完整打印响应
			
			if (res.status === "success") {
				showNotification(res.message || `图片上传成功：${res.file_name}`, "success");
				// showNotification(`保存路径：${res.file_path}`, "info");

				// 新增：触发自定义事件，将 "@Image" 传递给父组件
				const event = new CustomEvent('imageUploaded', { 
					detail: { 
						imageText: "@Image" 
					} 
				});
				window.dispatchEvent(event);

				selectedFile = null;
				imageUploaded = true;

				// 2秒后自动关闭抽屉
				autoCloseTimer = setTimeout(() => {
					hidden6 = true;
				}, 2000) as unknown as number;

				// 重置文件输入
				const fileInput = document.getElementById(
					"imageUpload"
				) as HTMLInputElement;
				if (fileInput) fileInput.value = "";
			} else {
				const errorMessage = res.message || "图片上传失败，请重试";
				showNotification(`上传失败：${errorMessage}`, "error");
			}
		} catch (error) {
			const errorMsg = error instanceof Error ? error.message : String(error);
			console.error('上传错误:', error); // 增加错误日志
			showNotification(`上传出错：${errorMsg}`, "error");
		} finally {
			uploading = false;
		}
	}

	function showNotification(text: string, type: string) {
		addNotification({
			text: text,
			position: "top-left",
			type: type,
			removeAfter: 3000,
		});
	}

    // 重置上传状态的函数
	function resetUploadStatus() {
		imageUploaded = false;
		selectedFile = null;
		
		// 清除自动关闭定时器
		if (autoCloseTimer) {
			clearTimeout(autoCloseTimer);
			autoCloseTimer = null;
		}
	}

	// 自定义关闭处理函数，不重置状态
	function handleDrawerClose() {
		hidden6 = true;
	}

	//上传文件
	$: files = $storageFiles ? $storageFiles : [];
	let hidden7 = true;

	async function handleKnowledgePaste(
		e: CustomEvent<{ pasteUrlList: string[] }>
	) {
		uploading = true;
		try {
			const pasteUrlList = e.detail.pasteUrlList;
			const res = await fetchKnowledgeBaseIdByPaste(pasteUrlList);
			handleUploadResult(res, "knowledge_base");
		} catch {
			handleUploadError();
		}
	}

	async function handleKnowledgeUpload(e: CustomEvent<any>) {
		uploading = true;
		try {
			// 这里依然对单个文件进行处理
			const blob = await fetch(e.detail.src).then((r) => r.blob());
			const fileName = e.detail.fileName;
			const res = await fetchKnowledgeBaseId(blob, fileName);
			handleUploadResult(res, fileName);
		} catch {
			handleUploadError();
		}
	}

	async function handleUploadResult(res: Response, fileName: string) {
		if (res.status === 200) {
			knowledge1.set({ id: "default" });
			knowledgeName.set(fileName);
			showNotification("Uploaded successfully", "success");
			// update fileStructure
			const res = await fetchAllFile();
			uploading = false;
			console.log("handleUploadResult", res);
			if (res) {
				const userUploadedFiles = res.map((file) => ({
					...file,
					isUserUploaded: true, // 标志为用户上传的文件
				}));
				storageFiles.set(userUploadedFiles);
				files = $storageFiles;
			}
		} else {
			//showNotification("Uploaded failed", "error");
		}
	}

	function handleUploadError() {
		//showNotification("Uploaded failed", "error");
	}

	// 点击外部关闭下拉框
	// onClickOutside(dropdownRef, () => (isOpen = false));

	// 处理上传文档的事件
	function handleUpload(event) {
		// 这里可以添加处理上传的逻辑
		console.log(event.detail); // 处理上传的文件
	}


	// 选项数据
	const options = [
		{ icon: "🖼️", label: "上传图片", accept: "image/*" },
		// { icon: "📂", label: "上传目录", accept: ".zip,.rar,.7z" },
		{ icon: "📄", label: "上传文档", accept: ".doc,.docx,.pdf" },
	];
</script>

<!-- 将按钮和下拉菜单包裹在一个相对定位的容器中 -->
<div class="relative inline-block">
	<button
		class="ml-2 rounded-lg bg-gray-100 p-2 text-white transition duration-200 hover:bg-gray-200 active:bg-gray-300"
		on:click={() => (isOpen = !isOpen)}
	>
		<svg
			class={classes}
			viewBox="0 0 1024 1024"
			version="1.1"
			xmlns="http://www.w3.org/2000/svg"
			p-id="1586"
			width="200"
			height="200"
		>
			<path
				d="M512 170.666667a341.333333 341.333333 0 1 0 0 682.666666 341.333333 341.333333 0 0 0 0-682.666666zM85.333333 512C85.333333 276.352 276.352 85.333333 512 85.333333s426.666667 191.018667 426.666667 426.666667-191.018667 426.666667-426.666667 426.666667S85.333333 747.648 85.333333 512z"
				fill="#8a8a8a"
				p-id="1587"
			/>
			<path
				d="M512 298.666667a42.666667 42.666667 0 0 1 42.666667 42.666666v128h128a42.666667 42.666667 0 1 1 0 85.333334h-128v128a42.666667 42.666667 0 1 1-85.333334 0v-128H341.333333a42.666667 42.666667 0 1 1 0-85.333334h128V341.333333a42.666667 42.666667 0 0 1 42.666667-42.666666z"
				fill="#8a8a8a"
				p-id="1588"
			/>
		</svg>
	</button>

	<!-- 下拉菜单 -->
	{#if isOpen}
		<div
			bind:this={dropdownRef}
			class="absolute bottom-full left-1/2 mb-2 w-40 -translate-x-1/2 transform rounded-2xl border border-gray-200 bg-white p-2 shadow-lg"
		>
			{#each options as option}
				<div
					class="flex cursor-pointer items-center rounded-lg px-4 py-2 transition hover:bg-gray-100"
					on:click={() => {
						if (option.label === "上传图片") {
							// handleImageUpload();
							hidden6 = false;
							resetUploadStatus(); // 重置上传状态
						}
						if (option.label === '上传文档') {
							hidden7 = false;
						}
					}}
				>
					<span class="text-lg">{option.icon}</span>
					<span class="ml-2 flex-1 text-gray-700">{option.label}</span>
				</div>
			{/each}
		</div>
	{/if}
</div>

{#if showUploadImage}
	<UploadImage />
{/if}
<Drawer
	backdrop={false}
	placement="right"
	transitionType="fly"
	transitionParams={transitionParamsRight}
	bind:hidden={hidden6}
	class="border-2 border-b-0 border-r-0 shadow"
>
	<div class="flex items-center">
		<h5
			class="mb-4 inline-flex items-center text-base font-semibold text-gray-500 dark:text-gray-400"
		>
			<InfoCircleSolid class="me-2.5 h-4 w-4" />图片上传
		</h5>
		<CloseButton on:click={handleDrawerClose} class="mb-4 dark:text-white" />
	</div>

	<div class="mb-6">
		<input
			type="file"
			id="imageUpload"
			accept="image/*"
			on:change={handleFileSelect}
			disabled={imageUploaded}
			class="block w-full cursor-pointer rounded-lg border border-gray-300 bg-gray-50 text-sm text-gray-900 focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:text-gray-400 dark:placeholder-gray-400 {imageUploaded
				? 'cursor-not-allowed opacity-50'
				: ''}"
		/>
	</div>

	{#if selectedFile}
		<div class="mb-6">
			<p class="text-sm text-gray-500">已选择文件: {selectedFile.name}</p>
		</div>
	{/if}

	<Button
		on:click={handleImageUpload}
		disabled={!selectedFile || uploading || imageUploaded}
		class="w-full"
	>
		{#if uploading}
			上传中...
		{:else if imageUploaded}
			已上传
		{:else}
			上传图片
		{/if}
	</Button>
</Drawer>

<Drawer
	backdrop={false}
	placement="right"
	transitionType="fly"
	transitionParams={transitionParamsRight}
	bind:hidden={hidden7}
	class=" border-2 border-b-0 border-r-0 shadow"
	id="sidebar6"
>
	<div class="flex items-center">
		<h5
			id="drawer-label"
			class="mb-4 inline-flex items-center text-base font-semibold text-gray-500 dark:text-gray-400"
		>
			<InfoCircleSolid class="me-2.5 h-4 w-4" />Data Source
		</h5>
		<CloseButton
			on:click={() => (hidden7 = true)}
			class="mb-4 dark:text-white"
		/>
	</div>
	<p class="mb-6 text-sm text-gray-500 dark:text-gray-400">
		Please upload your local file or paste a remote file link, and Chat will
		respond based on the content of the uploaded file.
	</p>

	<Tabs
		style="full"
		defaultClass="flex rounded-lg divide-x rtl:divide-x-reverse divide-gray-200 shadow dark:divide-gray-700 focus:ring-0"
	>
		<TabItem class="w-full" open>
			<span slot="title">Upload File</span>
			<UploadFile on:upload={handleKnowledgeUpload} />
		</TabItem>
		<TabItem class="w-full" data-testid="exchange-paste">
			<span slot="title">Paste Link</span>
			<PasteURL on:paste={handleKnowledgePaste} />
		</TabItem>
	</Tabs>
	{#if uploading}
		<div class="my-6 flex flex-col items-center justify-center">
			<LoadingButton />
		</div>
	{/if}

	{#if files.length > 0}
		<DocCard {files} />
	{:else}
		<div class="mt-6 flex flex-col items-center justify-center">
			<NoFile />
			<p class=" text-sm opacity-70">No files uploaded</p>
		</div>
	{/if}
</Drawer>
